package com.lemon.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.lemon.domain.Role;
import com.lemon.util.MybatisUtils;

public class RoleDao {

	/**
	 * 查找Role
	 * @param id
	 * @return
	 */
	public Role get(Long id) {
		SqlSession session = MybatisUtils.getSession();
		Role r = session.selectOne("com.lemon.mapper.RoleMapper.get", id);
		session.close();

		return r;
	}
	
	/**
	 * 查找所有角色
	 * @return
	 */
	public List<Role> list() {
		SqlSession session = MybatisUtils.getSession();
		List<Role> list;
		
		try {
			list = session.selectList("com.lemon.mapper.RoleMapper.list");
		} finally {
			session.close();
		}

		return list;
	}
	
	/**
	 * 插入
	 * @param r
	 * @return
	 */
	public Long save(Role r) {
		SqlSession session = MybatisUtils.getSession();
		
		try {
			session.insert("com.lemon.mapper.RoleMapper.save", r);
			session.commit();
		} finally {
			session.close();
		}
		
		return r.getId();
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	public int delete(Long id) {
		SqlSession session = MybatisUtils.getSession();
		int rows;
		
		try {
			rows = session.delete("com.lemon.mapper.RoleMapper.delete", id);
			session.commit();
		} finally {
			session.close();
		}
		
		return rows;
	}
	
	/**
	 * 修改
	 * @param r
	 * @return
	 */
	public int update(Role r) {
		SqlSession session = MybatisUtils.getSession();
		int rows;
		
		try {
			rows = session.update("com.lemon.mapper.RoleMapper.update", r);
			if (rows == 1) {// 如果没有记录被修改，那么该事物就不用提交了
				session.commit();
			} 
		} finally {
			session.close();
		}
		
		return rows;
	}
}
